<?php #Редактор таблиц
class table_editor extends Load_use
{
	private  $count=0;
	function getBlock()
	{
		if(!isset($this->params['can_edit'])||empty($this->params['select'])||empty($this->params['fields']))
			return false;
		/*Можно редактировать*/
		$can_edit=$this->params['can_edit'];
		if(empty($this->params['update']))
			$can_edit=false;
		/*Можно добавлять*/
		$can_add=$can_edit && !empty($this->params['insert']);
		
		$post=array();
		$this_name='te_'.$this->count;
		$session_name=$this_name;
		$pagination_param='pn'.$this->count;
		if(isset($_GET['p']))
			$session_name.=$_GET['p'];
		if(isset($_POST[$this_name]))
		{
			$redirect=false;
			$post=$_POST[$this_name];
			/*Обновить*/
			if($can_edit && !empty($post['edit']) && preg_match_all('@(#(([^#|]+)\||)([^#]+)#)@',$this->params['update'],$res,PREG_SET_ORDER))
			{
				$replace_fields=array();
				$fields=array();
				$repl_count=0;
				$functions=array();
				foreach($res as $i=>$val)
				{
					$replace_fields[$i]=$val[1];
					/*Функция обработки поля*/
					if($val[3])
						$functions[$i]=$val[3];						
					$fields[$i]=$val[4];
					if($val[4]!='sys_id')
						$repl_count++;
				}
				foreach($post['edit'] as $id=>$row)
				{
					if(count($row)!=$repl_count)
					{
						$this->add_log('Не совпадает количество параметров формы с запросом редактирования <br />'.$this->params['update'],DEE_ERROR);
						continue;
					}
					$replace=array();
					$good=true;
					foreach($fields as $i=>$field)
						if($field=='sys_id')
							$replace[$i]=$id;
						elseif(!isset($row[$field]))
						{
							$good=false;
							break;
						}
						elseif(isset($functions[$i]))
						{
							$func=$functions[$i];
							$replace[$i]=mysql_escape_string($func($row[$field]));
						}
						else
							$replace[$i]=mysql_escape_string(trim($row[$field]));
					
					if($good)
					{
						$redirect=true;						
						$this->conn->query(str_replace($replace_fields,$replace,$this->params['update']));					
					}
				}
			}
			/*Добавить*/
			if($can_add && !empty($post['add']))
			{
				$insert=$this->params['insert'];
				if(!is_array($insert))	
					$insert=array($insert);
				$good=true;
				$replace_fields=array();
				$fields=array();
				$functions=array();
				foreach($insert as $id=>$insert_q)
					if(preg_match_all('@(#(([^#|]+)\||)([^#]+)#)@',$insert_q,$res,PREG_SET_ORDER))
					{
						$replace_fields[$id]=array();
						$functions[$id]=array();
						$fields[$id]=array();
						foreach($res as $i=>$val)
						{
							$replace_fields[$id][$i]=$val[1];
							/*Функция обработки поля*/
							if($val[3])
								$functions[$id][$i]=$val[3];						
							$fields[$id][$i]=$val[4];
						}
					}
					else
					{
						$good=false;
						break;
					}
				if($good)
				{
					foreach($post['add'] as $row_id=>$row)
					if($row_id!='#')
					{
						$replace_ids=array();
						$replace_id_vals=array();
						$qCount=0;
						foreach($insert as $id=>$insert_q)
						{	
							$replace_f=$replace_ids;
							$replace=$replace_id_vals;
							$functions_f=array();
							$good=true;
							foreach($fields[$id] as $i=>$field)
								if($field=='sys_id')
								{
									if(isset($functions[$id][$i]))
										$functions_f[$i]=$functions[$id][$i];
									$replace_f[$i]=$replace_fields[$id][$i];
									$replace[$i]=$id;
								}
								elseif(!isset($row[$field]))
								{
									if(!in_array("#$field#",$replace_ids))
									{
										$good=false;			
										break;
									}
								}
								else
								{
									$replace_f[$i]=$replace_fields[$id][$i];
									if(isset($functions_f[$i]))
									{
										$func=$functions_f[$i];
										$replace[$i]=mysql_escape_string($func(trim($row[$field])));
									}										
									else
									$replace[$i]=mysql_escape_string(trim($row[$field]));
									
								}	
								
							if(!empty($replace[$i]) && $good && (!empty($replace)||$qCount++>0))
							{			
								$replace_ids[]="#$id#";
								$redirect=true;
								$replace_id_vals[]=$this->conn->query(str_replace($replace_f,$replace,$insert_q),true);	
								
							}
							else break;
						}
					}
				}
			}
			/*Удалить*/
			if($can_add && !empty($post['delete']) && $d_query=$this->getParam('delete',false))
			{
				if(!is_array($d_query))
					$d_query=array($d_query);
					$ids=array();
				foreach($post['delete'] as $id=>$v)
					$ids[]=$id;
				$ids=implode(',',$ids);
				foreach($d_query as $q)
					$this->conn->query(str_replace('#sys_ids#',$ids,$q));
					
			}
			unset($post['add']);
			unset($post['delete']);
			unset($post['edit']);
			$_SESSION['table_editor'][$session_name]=$post;
			if(!$this->getParam('dev',false) && $redirect)successRedirect();
		}
		elseif(isset($_SESSION['table_editor'][$session_name]))
		{
			$post=$_SESSION['table_editor'][$session_name];
		}
		$head='';
		$filter='';
		$sort='<option></option>';
		$to_js=array();
		$sort_by=isset($post['params']['sort'])?$post['params']['sort']:false;
		/*Главный идентификатор для удаления и обновления*/
		$sys_id=false;
		$select=array();
		$query_filter='';
		$add_prot='';
		if($can_add)
			$add_prot.='<tr class="add_prototype row"><td class="td_hidden"></td>';
		$params_to_js=array();
		/*Формирую заголовок, фильтр , массив для js и прототип*/
		foreach($this->params['fields'] as $name=>$param)
		{
			/*показывать толко при редактировании*/
			$hidden=isset($param['hidden']);
			if($hidden&&!$can_edit)continue;
			$to_edit=!isset($param['to_edit']);
			if(isset($param['sys_id']))
				$sys_id=$name;
			/*Название для запроса*/
			$query_name=(isset($param['query_name'])?$param['query_name'] .' as ':'').$name;
			
			/*Параметры для поля ввода*/
			$f_params=$param;
			if($hidden)
				$add_prot.='<td class="hidden"></td>';
			elseif($can_add && $to_edit)
			{
				$f_params['name']=$this_name.'[add][#]['.$name.']';	
				
				$add_prot.='<td>'.$this->load->block('form_element',$f_params).'</td>';
			}
			elseif($can_add)
				$add_prot.='<td class="not_to_edit"></td>';
			$f_params['name']=$this_name.'[filter]['.$query_name.']';	
			$f_params['class']='autosubmit';
			if(!empty($f_params['values']))
				$f_params['values']=array_merge(array(''=>''),$f_params['values']);
			if(!empty($post['filter'][$query_name]))
			{
				$f_params['val']=$post['filter'][$query_name];
				$q_name=isset($param['query_name'])?$param['query_name']:$name;
				$query_filter.=" and $q_name like '%{$f_params['val']}%'";
			}
			$select[$name]=$query_name;			
			
			/*Заголовок*/
			$title=empty($param['title'])?'':$param['title'];
			if($hidden)
				$filter.='<td class="hidden"></td>';
			elseif($to_edit || isset($f_params['type']))
			{
				$sort.='<option value="'.$query_name.($sort_by==$query_name?'" selected="selected':'').'">'.$title.'</option>';
				$filter.='<td'.(!$to_edit?' class="not_to_edit"':'').'>'.$this->load->block('form_element',$f_params).'</td>';
			}
			else	
				$filter.='<td class="not_to_edit"></td>';
			
			$this->params['fields'][$name]=$param;			
			unset($param['link']);				
			$params_to_js[$name]=$param;
			$head.='<td name="'.$name.($hidden?'" class="hidden':(!$to_edit?'" class="not_to_edit':'')).(isset($param['width'])?'" width="'.$param['width']:'').'" >'.$title.'</td>';
		}
		if($can_add)
			$add_prot.='</tr><tr class="row row_add"><td colspan="'.(count($this->params['fields'])+1).'">'.$this->load->block('buttons',array('style'=>'add','attr'=>'onclick ="form_control_function(this,\'row\',\'#\');te_add_func(this)" btype="add"','text'=>'Добавить')).'</td></tr>';
		$js_arr=($this->count==0?'var fe_fiedlds_arr=[];':'').'fe_fiedlds_arr['.$this->count.']='.getJSArr($params_to_js);
		
		
		$where=isset($this->params['select']['where'])?$this->params['select']['where']:1;
		
		$replace_links=false;
		if(isset($this->params['link_replaces']))
		{
			if(isset($param['replace']))
			{
				foreach($this->params['link_replaces'] as $bn=>$n)
					$select[$n]=(is_numeric($bn)?'':$bn.' as ').$n;
			} 
			$replace_links=array();
			foreach($select as $i=>$val)
				$replace_links[]="#$i#";
		} 
		$select=implode(',',$select);
		$select="select sql_calc_found_rows $select from {$this->params['select']['from']} where $where $query_filter";
		if($sort_by)
			$select.=" order by $sort_by";
		$limit_count=isset($post['params']['limit'])?$post['params']['limit']:10;
		if($limit_count!='all')
		{
			$start_count=isset($_GET[$pagination_param])?($_GET[$pagination_param]-1)*$limit_count:0;
			$select.=" limit $start_count,$limit_count";
		}
		$show_filter=isset($post['params']['filter'])?$post['params']['filter']:false;
		$data='';
		$this->conn->query($select);
		$even_counter=0;
		while($row=$this->conn->fetch())
		{
			$id=0;
			if($sys_id && isset($row->$sys_id))
				$id=$row->$sys_id;
			$data.='<tr f_id="'.$id.($even_counter++%2==0?'" class="even':'').'">';
			if($can_edit)
			{
				if($id)
					$data.='<td class="td_hidden">'.$this->load->block('form_element',array('type'=>'checkbox','name'=>$this_name.'[delete]['.$id.']','class'=>'edit delete')).'</td>';
				else
					$data='<td></td>';					
			}
			foreach($this->params['fields'] as $field_name=>$param)
			{
				$hidden=isset($param['hidden']);
				if($hidden&&!$can_edit)continue;
				$to_edit=!isset($param['to_edit']);
				$param['to_edit']=true;
				if(isset($param['link']))
				{
					if($replace_links)
					{
						$arr=array();
						foreach($row as $i=>$val)
							$arr[]=$val;
						$param['val']=str_replace($replace_links,$arr,$param['link']);
					}
					else
						$param['val']=$param['link'];
					
				}
				else
					$param['val']=isset($row->$field_name)?$row->$field_name:''; 
				$data.='<td'.($hidden?' class="hidden"':(!$to_edit?' class="not_to_edit"':'')).'>'.$this->load->block('form_element',$param).'</td>';
			}
			$data.='</tr>';
		}
		$this->conn->query('select found_rows() as r');		
		$selected_count=$this->conn->fetch();
		$selected_count=$selected_count->r;
		if($limit_count=='all')
			$limit_count=$selected_count;
		$limit=$this->load->block('form_element',array('type'=>'radio','values'=>array(1=>1,10=>10,50=>50,100=>100,'all'=>'Все('.$selected_count.')'),'val'=>$limit_count,'name'=>$this_name.'[params][limit]','class'=>'autosubmit limit'));
		$control_functions=array('edit');
		if(!empty($this->params['delete']))
			$control_functions[]='delete';
		return '<div class="form table_editor"><div class="controll"><form action="" method="post">'
		
		.$this->load->block('form_element',array('type'=>'checkbox','val'=>$show_filter,'desc'=>'Фильтр','attr'=>'onChange="te_filterShowHide(this)"','name'=>$this_name.'[params][filter]'))		
		 .' Сортировать по: <select name="'.$this_name.'[params][sort]"  class="autosubmit sort">'
			.$sort
		 .'</select>
		Вывести: '
			.$limit
	.'</div>
	</form>
	<form action="" count="'.$this->count++.'" class="editor_block"  id="table_editor" name="'.$this_name.'" method="post">'
	.$this->load->block('form_control',array('controls'=>$control_functions,'title'=>$this->getParam('control_name','Редактор таблиц')))
	.'<div class="clear"></div><table class="to_save" id="te_pag-'.$this->count.'">
		<thead>
			<tr class="filter'.($show_filter?'':'" style="display:none').'">'
				.($can_edit?'<td class="td_hidden"></td>':'')
				.$filter
			.'</tr>			
			<tr class="head">'
				.($can_edit?'<td class="td_hidden"></td>':'')
				.$head
			.'</tr>
		</thead>
		<tbody>'
			.$data
			.$add_prot
		.'</tbody>
	</table>
</form></div>'
	.$this->load->block('pagination',array('total'=>$selected_count,'url_after'=>'#te_pag-'.$this->count,'limit'=>$limit_count,'pagination_param'=>$pagination_param))
.'<script type="text/javascript">'
	.$js_arr
.'</script>';
	}
}